package com.cfoco.util;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author syd
 * @create 2020-09-07 7:59
 */
//@PropertySource(value={"classpath:application.properties"})
public class ImageUtil {

    //@Value("{application.imgPath}")
    @Value("${imgPath}")
    private String imgPath;

    /**
     * 一般工具类为静态方法，不能使用外部变量，暂时定义为非静态方法
     * @param request
     * @param file
     * @return
     * @throws IOException
     */

    public String upload(HttpServletRequest request, MultipartFile file) throws IOException {

        String imagePath=null;

        //上传图片
        if(file!=null && !file.isEmpty()){
            //UUID文件名
            String name = UUID.randomUUID().toString().replaceAll("-", "");
            //文件扩展名
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());
            //上传路径
            String url = request.getSession().getServletContext().getRealPath(imgPath);
            //检验文件夹是否存在
            isFolderExists(url);
            //以绝对路径保存重命名后的图片
            file.transferTo(new File(url+"/"+name+"."+ext));
            //图片地址
            imagePath=imagePath+name+"."+ext;
        }
        return imagePath;
    }

    /**
     * 判断目录是否存在
     * @param url
     * @return
     */
    private static boolean isFolderExists(String url) {

        File file=new File(url);
        if(!file.exists()){
            if(file.mkdir()){
                return true;
            }else{
                return false;
            }
        }
        return true;
    }

    public static List<File> getFileSort(String path){
        List<File> list=getFiles(path,new ArrayList<File>());
        if(list!=null && list.size()>0){
            Collections.sort(list, new Comparator<File>() {
                @Override
                public int compare(File o1, File o2) {
                    if(o1.lastModified()<o2.lastModified()){
                        return 1;
                    }else if(o1.lastModified()==o2.lastModified()){
                        return 0;
                    }else{
                        return -1;
                    }
                }
            });
        }
        return list;
    }

    public static List<File> getFiles(String realPath,List<File> files){

        File realFile=new File(realPath);
        if(realFile.isDirectory()){
            File[] realfiles = realFile.listFiles();
            for(File file:realfiles){
                if(file.isDirectory()){
                    getFiles(file.getAbsolutePath(),files);
                }else{
                    files.add(file);
                }
            }
        }
        return files;
    }
}
